// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace svs.Mobile.BeyondMedia.FeedCore.RSS.Templates
{
	public abstract class TemplateBase
	{
		public enum TemplateTypes
		{
			RSS,
			TTS
		}
    
		protected Dictionary<string, string> m_Parameters = new Dictionary<string, string>();
		protected string m_TemplateFileName;
		protected TemplateTypes m_TemplateType = TemplateTypes.RSS;

		protected TemplateBase(TemplateTypes type)
		{
			m_TemplateType = type;
		}

		public TemplateTypes TemplateType
		{
			get
			{
				return m_TemplateType;
			}
		}

		public virtual List<KeyValuePair<string, string>> Template
		{
			get { throw new NotSupportedException("Must override in a child class"); }
		}

		/// <summary>
		///  Executes a template transformation
		/// </summary>
		/// <returns></returns>
		public virtual void ToHtml(StreamWriter writer)
		{
			ApplyParameters(writer);
		}

		protected List<KeyValuePair<string, string>> LoadTemplate()
		{
			string tmpFile = Path.Combine(m_TemplateType == TemplateTypes.RSS ? Configuration.RssTemplatesPath : Configuration.TTSTemplatesPath, m_TemplateFileName);
			string retVal = null;

			if (File.Exists(tmpFile))
			{
				using (StreamReader sr = File.OpenText(tmpFile))
				{
					retVal = sr.ReadToEnd();
					sr.Close();
				}

				return ParseTemplate(retVal);
			}
			else
			{
				CoreHelper.WriteLogEntry("Template " + tmpFile + " does not exist!");
			}

			return new List<KeyValuePair<string, string>>();
		}

		private static List<KeyValuePair<string, string>> ParseTemplate(string val)
		{
			var retVal = new List<KeyValuePair<string, string>>();

			Regex regex = new Regex(
				@"(?<Key>\x23[A-Z_]*\x23)",
				RegexOptions.IgnoreCase
				| RegexOptions.Multiline
				| RegexOptions.IgnorePatternWhitespace
				| RegexOptions.Compiled
				);
			MatchCollection matches = regex.Matches(val);
			int start = 0;
			foreach (Match match in matches)
			{
				KeyValuePair<string, string> pair =
					new KeyValuePair<string, string>(val.Substring(start, match.Index - start), match.Value);
				start = match.Index + match.Length;
				retVal.Add(pair);
			}

			KeyValuePair<string, string> final = new KeyValuePair<string, string>(val.Substring(start),null);
			retVal.Add(final);

			return retVal;
		}

		protected void ApplyParameters(StreamWriter writer)
		{
			if (Template == null)
			{
				writer.Write(("Template file " + Path.Combine(Configuration.RssTemplatesPath, m_TemplateFileName) +
				              " does not exist!"));
			}

			foreach (KeyValuePair<string, string> pair in Template)
			{

				if(!string.IsNullOrEmpty(pair.Key))
					writer.Write(pair.Key);

				if(!string.IsNullOrEmpty(pair.Value))
				{
					if(m_Parameters.ContainsKey(pair.Value))
					{
						writer.Write(m_Parameters[pair.Value]);
					}
				}
			}
		}

		protected void WriteTemplateFor(KeyValuePair<string, string> pair, StreamWriter sr)
		{
			if (!string.IsNullOrEmpty(pair.Key))
				sr.Write(pair.Key);

			if (!string.IsNullOrEmpty(pair.Value))
				WriteContentFor(pair.Value, sr);
		}

		protected virtual void WriteContentFor(string key, StreamWriter sr)
		{
			if (!string.IsNullOrEmpty(key))
			{
				if (m_Parameters.ContainsKey(key))
				{
					sr.Write(m_Parameters[key]);
				}
			}
		}
	}
}